package com.hn658.base.message.notification.notify.business.impl;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hn658.base.message.common.dto.NotificationDTO;
import com.hn658.base.message.common.enums.NotifySenderType;
import com.hn658.base.message.common.enums.NotifyType;
import com.hn658.base.message.notification.notify.business.INotificationManager;
import com.hn658.base.message.notification.notify.dao.redis.INotifyRedisDAO;
import com.hn658.base.message.notification.notify.entity.TalkerEO;
import com.hn658.base.message.notisender.business.INotisenderManager;
import com.hn658.base.message.notisender.message.APNSMessage;
import com.hn658.base.message.notisender.message.AndroidMessage;
import com.hn658.base.message.notisender.message.CometMessage;
import com.hn658.base.message.notisender.sender.comet.IIsOnlineManager;
import com.hn658.base.message.notisender.utils.IDeviceTokenManager;
import com.hn658.framework.shared.utils.JsonMapper;

/**
 * Created by baihai on 2015/11/26.
 */
@Component
public class NotificationManagerImpl extends AbstartNotifiCationManager implements INotificationManager{


    /**
     * 日志记录器
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private JsonMapper jsonMapper = JsonMapper.nonEmptyMapper();

    @Autowired
    private INotisenderManager notisenderManager;

    @Autowired
    private IIsOnlineManager isOnlineManager;

    @Autowired
    private IDeviceTokenManager deviceTokenManager;

    @Autowired
    private INotifyRedisDAO notifyRedisDAO;
    
    /**
     * 单聊发送
     * @param notificationDTO
     */
    @Override
    public void send(NotificationDTO notificationDTO){
    	this.send(notificationDTO, true);
    }
    
    /**
     * 单聊发送
     * @param notificationDTO
     */
    @Override
    public void send(NotificationDTO notificationDTO, boolean isOfflineSend){
        logger.debug("开始准备推送消息{}", notificationDTO);
        boolean isOnline = isOnlineManager.isonline(notificationDTO.getAppId(),notificationDTO.getToUid()+"");
        if(isOnline){
            //用户在线
            sendComet(notificationDTO);
        }else{
        	if(isOfflineSend){
        		//用户不在线
        		String apnsToken = deviceTokenManager.getApnsToken(notificationDTO.getAppId(), notificationDTO.getToUid()+"");
        		Long channelId = deviceTokenManager.getChannelId(notificationDTO.getAppId(), notificationDTO.getToUid()+"");
        		String userId = deviceTokenManager.getUserId(notificationDTO.getAppId(), notificationDTO.getToUid()+"");
        		if(channelId!=null&& StringUtils.isNotBlank(userId)){
        			sendAndroid(notificationDTO,userId,channelId);
        		}
        		if(StringUtils.isNotBlank(apnsToken)){
        			sendAPNS(notificationDTO,apnsToken);
        		}        		
        	}
        }
    }

    private void sendComet(NotificationDTO notificationDTO){
        CometMessage message = new CometMessage();
        message.setDto(notificationDTO);
        message.setNotifyType(notificationDTO.getNotifyType());
        notisenderManager.sendNotification(message);
    }


    private void sendAndroid(NotificationDTO notificationDTO,String userId,Long channelId){
        AndroidMessage androidMs = new AndroidMessage();
        String contentJson = jsonMapper.toJson(notificationDTO);
        androidMs.setContent(contentJson);
        androidMs.setType(NotifySenderType.Android);
        androidMs.setChannelId(channelId);
        androidMs.setUserId(userId);
        notisenderManager.sendNotification(androidMs);
    }

    private void sendAPNS(NotificationDTO notificationDTO,String apnsToken){
        // 创建ANPS Notification消息
        APNSMessage APNSMessage = new APNSMessage();
        APNSMessage.setToken(apnsToken);
        APNSMessage.setDestination(notificationDTO.getToUid().toString());
        APNSMessage.setContent(notificationDTO.getMsg());
        APNSMessage.setBadgeCount(notificationDTO.getUnReadCount());
        // 通知
        notisenderManager.sendNotification(APNSMessage);
    }


	@Override
	public boolean currentTalk(String appId, String uid, String toId,
			NotifyType type) {
		//查出缓存中用户当前聊天对象
		TalkerEO talkerEO = notifyRedisDAO.getTalker(appId, uid);
		if(talkerEO!=null){
			//判断聊天类型是否相同
			if(talkerEO.getNotifyType()==type.getValue()){
				//判断聊天对象id是否相同
				if(talkerEO.getToId()==toId){
					return true;
				}
			}
		}
		return false;
	}


	@Override
	public void saveTalker(String appId, String uid, String toId, NotifyType type) {
		TalkerEO talk = new TalkerEO();
		talk.setToId(toId);
		talk.setNotifyType(type.getValue());
		notifyRedisDAO.saveTalker(appId, uid, talk);
	}


	@Override
	public int getUnReadCountByNotiId(String appId, String uid, String notifyId) {
		return notifyRedisDAO.getNotiReadCount(appId, uid, notifyId);
	}


	@Override
	public void saveUnReadCountByNotiId(String appId, String uid,
			String notifyId, int count) {
		notifyRedisDAO.setNotiReadCount(appId, uid, notifyId, count);
	}



}
